import aioredis
import asyncio
from biz_code.component import on_setup_config


class Redis:
    _redis = None

    async def get_redis_pool(self, *args, **kwargs):
        if not self._redis:
            self._redis = await aioredis.from_url(
                'redis://' + on_setup_config.config["redis"]["host"],
                username=on_setup_config.config["redis"]["user"],
                password=on_setup_config.config["redis"]["password"],
                port=on_setup_config.config["redis"]["port"],
                db=on_setup_config.config["redis"]["db"]
            )
            # self._redis = await aioredis.create_redis_pool((
            #     redis_config.host, redis_config.port),
            #     db=redis_config.db, password=redis_config.password
            # )

        return self._redis

    async def close(self):
        if self._redis:
            await self._redis.close()


async def get_value(key):
    redis = Redis()
    r = await redis.get_redis_pool()
    # d = await r.set("aaa", "bbb", ex=10, px=True)
    d = await r.set("bbb", "ccc", ex=10, nx=True)
    print(d)
    value = await r.get(key)
    print(f'{key!r}: {value!r}')
    await redis.close()


if __name__ == '__main__':
    l = asyncio.get_event_loop()
    l.run_until_complete(get_value("hhh"))
